<template>
  <div class="mod-config">
    <el-collapse>
      <el-collapse-item>
        <template slot="title">
          <span class="span_title">项目基本信息</span>
        </template>
        <div style="background-color: #f0f0f0">
          <div><strong>项目名称：</strong>{{projectInfo.projectName}}</div>
          <div><strong>项目类型：</strong>{{projectInfo.projectType}}</div>
          <div><strong>合同名称：</strong>{{projectInfo.contractName}}</div>
          <div><strong>委托单位：</strong>{{projectInfo.projectAuthorize}}</div>
          <div><strong>委托要求：</strong>{{projectInfo.projectNote}}</div>
          <div><strong>生产负责人：</strong>{{projectInfo.projectProduce}}</div>
          <div><strong>业务负责人：</strong>{{projectInfo.projectBusiness}}</div>
          <div><strong>项目负责人：</strong>{{projectInfo.projectCharge}}</div>
          <div><strong>工作内容：</strong>{{projectInfo.workNote}}</div>
          <div><strong>工作要求：</strong>{{projectInfo.workRequire}}</div>
          <div><strong>工作小结：</strong>{{projectInfo.briefSummary}}</div>
          <div style="display:flex;padding-bottom: 4px;"><strong>项目清单：</strong>
            <el-table :data="projectInfo.projectBillList" border >
              <el-table-column prop="billName" header-align="center" align="center" label="项目" ></el-table-column>
              <el-table-column prop="spec" header-align="center" align="center" label="规格"></el-table-column>
              <el-table-column prop="num" header-align="center" align="center" label="数量" ></el-table-column>
              <el-table-column prop="remark" header-align="center" align="center" label="备注"></el-table-column>
            </el-table>
          </div>
        </div>
      </el-collapse-item>
    </el-collapse>

    <el-card style="margin-top: 20px;">
      <el-tabs type="card" @tab-click="tabsHandleClick" v-model="activeName">
        <!--提交成果-->
        <el-tab-pane label="提交成果" name="first" >
            <el-card :body-style="{ padding: '3px' }" style="border: 1px solid cornflowerblue">
              <div slot="header" class="clearfix" >
                <div class="ach_title">
                  <span class="span_title">成果文件</span>
                  <el-button type="primary" size="large" icon="el-icon-refresh" @click="init">刷新</el-button>
                </div>
              </div>
              <div class="section" v-loading="loading" >
                <div class="section_404" v-if="!isConnected">
                  <el-image :src="require('@/assets/img/others/404.png')" style="padding: 5px;"></el-image>
                </div>
                <div v-else class="file_section">
                  <el-button type="primary" icon="el-icon-plus" @click="addProFileHandle">新增上传</el-button>
                  <el-table :data="projectFiletList" border :header-cell-style="{background: 'steelblue',color:'white',fontSize: '11pt'}">
                    <el-table-column prop="fileName" header-align="center" align="left" label="上传记录名称" :key="bTabKey">
                      <template slot-scope="scope">
                        <div class="file_item_name" @dblclick="scope.row.isFouce? '':lookoverFileHandle(scope.row)">
                          <i><icon-svg :name="getFileType(scope.row)" ></icon-svg></i>
                          <input v-if="scope.row.isFouce" v-model="scope.row.fileName" v-focus @blur="blurArchHandle(scope.row)"></input>
                          <strong v-else>{{scope.row.fileName}}</strong>
                        </div>
                      </template>
                    </el-table-column>
                    <el-table-column prop="createUsername" header-align="center" align="left" label="创建人" width="100"></el-table-column>
                    <el-table-column prop="createTime" header-align="center" align="left" label="创建时间"></el-table-column>
                    <el-table-column prop="modifyUsername" header-align="center" align="left" label="修改人" width="100"></el-table-column>
                    <el-table-column prop="modifyTime" header-align="center" align="left" label="更新时间"></el-table-column>
                    <el-table-column  header-align="center" align="left" label="操作" width="220">
                      <template slot-scope="scope">
                        <el-button type="primary" size="mini" @click="openProFileHandle(scope.row)">打开</el-button>
                        <el-button type="warning" size="mini" @click="editArchHandle(scope.row)">编辑</el-button>
                        <el-button type="danger" size="mini" @click="deletePfileHandle(scope.row),selectItem = null">删除</el-button>
          <!--                <el-button type="primary" size="small">-->
          <!--                  <el-badge is-dot v-if="scope.row.updateFlag">归档</el-badge>-->
          <!--                  <span v-else>归档</span>-->
          <!--                </el-button>-->
                      </template>
                    </el-table-column>
                  </el-table>
                  <!--列表-->
                  <uploader :options="options" ref="uploader" :file-status-text="statusText" class="uploader-example"
                            @file-success="onFileSuccess" @file-added="onFileAdd" @file-removed="onFileRemove" style="padding-top: 20px" v-if="selectItem !== null">
                    <!--      //浏览器不支持将显示此内容-->
                    <uploader-unsupport></uploader-unsupport>
                    <uploader-drop style="min-height: 200px;border: 1px solid cyan">
                      <el-row :gutter="5">
                        <div style="width: 100%;text-align: center;border: 1px solid #bebebe">
                          <div style="color: red;padding: 2px;text-decoration: underline"><span>*文件拖拽至此可上传*</span></div>
                          <div style="font-size: 15pt;background: #F0F0F0"><strong>{{selectItem.fileName}}</strong></div>
                          <el-table border :data="dataList" :header-cell-style="{background: '#F0F0F0'}">
                            <el-table-column prop="fileName" header-align="center" align="left" label="文件名">
                              <template slot-scope="scope">
                                <div class="file_item_icon" >
                                  <i style="font-size: 19pt;padding-top: 10px;"><icon-svg :name="getFileType(scope.row)" ></icon-svg></i>
                                  <span>{{scope.row.fileName}}</span>
                                </div>
                              </template>
                            </el-table-column>
                            <el-table-column prop="createUsername" header-align="center" align="left" label="上传者" width="100"></el-table-column>
                            <el-table-column prop="createTime" header-align="center" align="left" label="上传时间" width="160"></el-table-column>
                            <el-table-column prop="modifyUsername" header-align="center" align="left" label="修改人"  width="100"></el-table-column>
                            <el-table-column prop="modifyTime" header-align="center" align="left" label="更新时间" width="160"></el-table-column>
                            <el-table-column  header-align="center" align="left" label="操作"  width="100">
                              <template slot-scope="scope">
                               <el-button type="danger" size="small" style="padding-top: 10px;" @click="deletePfileHandle(scope.row)">删除</el-button>
          <!--                      <el-button type="primary" size="small">操作</el-button>-->
                              </template>
                            </el-table-column>
                          </el-table>
                        </div>
                      </el-row>
                    </uploader-drop>
                    <div class="popup-container">
                      <div class="header">
                        <div class="title_span">上传列表</div>
                        <div class="title_btn" >
                          <i class="el-icon-minus" @click="panelShow = false" v-if="panelShow"></i>
                          <i class="el-icon-copy-document" @click="panelShow = true" v-if="!panelShow"></i>
                        </div>
                      </div>
                      <uploader-list class="content" v-if="panelShow">
                        <div class="file-panel" slot-scope="props" >
                          <ul class="file-list">
                            <li v-for="file in props.fileList" :key="file.id">
                              <uploader-file :class="'file_' + file.id" ref="files" :file="file" :list="true"></uploader-file>
                            </li>
                            <div class="no-file" v-if="!props.fileList.length">
                              <div style="text-align: center;color: grey">--暂无待上传文件--</div>
                            </div>
                          </ul>
                        </div>
                      </uploader-list>
                    </div>
                  </uploader>
                </div>
              </div>
            </el-card>

        </el-tab-pane>
        <!--归档处理-->
        <el-tab-pane label="归档处理" name="second">
          <el-card :body-style="{ padding: '3px' }" style="border: 1px solid cornflowerblue">
            <div slot="header" class="clearfix" >
              <div class="ach_title">
<!--                <strong style="color: red">{{finalDirName}}</strong>-->
                <span class="span_title">归档文件</span>
                <el-button type="primary" size="large" icon="el-icon-refresh" @click="init">刷新</el-button>
              </div>
            </div>
            <div class="section" v-loading="loading" v-if="!loading">
              <div class="section_404" v-if="!isConnected">
                <el-image :src="require('@/assets/img/others/404.png')" style="padding: 5px;"></el-image>
              </div>
              <div v-else>
                <div style="width: 500px">
                  <el-table :data="projectFiletList" border >
                    <el-table-column prop="fileName" header-align="center" align="left" label="上传记录名称"></el-table-column>
                    <el-table-column prop="createUsername" header-align="center" align="left" label="创建人" width="100"></el-table-column>
                    <el-table-column  header-align="center" align="left" label="操作" width="100">
                      <template slot-scope="scope">
                        <el-button type="primary" size="mini" @click="openProFileHandle(scope.row)">打开</el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
                <div style="display: flex;width: 100%;padding: 10px;">
                  <div style="width: 500px;">
                    <strong style="color: red">（{{selectItem == null? '':selectItem.fileName}}）</strong>
                    <span>成果文件：</span>
                    <el-table :data="dataList" border @selection-change="selectionChangeHandle">
                      <el-table-column type="selection" header-align="center" align="center" width="50"></el-table-column>
                      <el-table-column prop="fileName" header-align="center" align="left" label="文件名">
                        <template slot-scope="scope">
                          <div class="file_item_name" >
                            <i><icon-svg :name="getFileType(scope.row)" ></icon-svg></i>
                            <strong>{{scope.row.fileName}}</strong>
                          </div>
                        </template>
                      </el-table-column>
                      <el-table-column prop="createUsername" header-align="center" align="left" label="创建人" width="100"></el-table-column>
                    </el-table>
                  </div>
                  <div style="padding-top: 30px;">
                    <el-button type="primary" @click="saveFinalFileHandle">归档至》</el-button>
                  </div>
                  <div style="width: 600px;">
                    <final-file ref="finalFile" :params="params"></final-file>
                  </div>
                </div>
              </div>
            </div>
          </el-card>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>

</template>

<script>
import Vue from 'vue'
import {stringIsNull} from '@/utils'
import {getFileType,getFileSize} from '@/utils/others/fileutils'
import finalFile from './final-file'

// 注册一个全局自定义指令 `v-focus`
Vue.directive('focus', {
  // 当被绑定的元素插入到 DOM 中时……
  inserted: function (el) {
    // 聚焦元素
    el.focus()
  }
})
export default {
  data () {
    return {
      dataLoading: false,
      projectNo: '',
      reportTitle: '',
      projectInfo: '',
      isConnected: true,
      loading: true,
      showImg: false,
      ipServer: '',
      panelShow: false,
      statusText: {
        success: '成功了',
        error: '出错了',
        uploading: '上传中',
        paused: '暂停中',
        waiting: '等待中'
      },
      aTabKey: '',  // 表格主键key
      bTabKey: '',
      proKey: '',
      dataListSelections: [],
      dataList: [],
      finalList: [],   // 归档文件列表
      finalDirName: '',  // 默认的归档文件夹名
      projectFiletList: [],
      selectItem: null, // 选择的记录文件
      contractItem: {}, // 对应的合同项
      timer: '', // 定时器
      options: {},
      activeName: 'first',
      processList: [],  // 进度列表
      curpath: [],
      isSearch: false,
      isCreated: false,
      params: {}
    }
  },
  components: {
    finalFile
  },
  computed: {
    argsPageIndex: {
      get () { return this.$store.state.paramsutil.argsPageIndex },
      set (val) { this.$store.commit('paramsutil/updateargsPageIndex', val) }
    },
    argsPageSize: {
      get () { return this.$store.state.paramsutil.argsPageSize },
      set (val) { this.$store.commit('paramsutil/updateargsPageSize', val) }
    },
    username: {
      get () { return this.$store.state.user.name }
    }
  },
  mounted () {
    this.init()
  },
  // 结束时候关闭定时器
  destroyed () {
    clearInterval(this.timer)
  },
  methods: {
    init () {
      this.projectNo = this.$route.query.projectNo
      this.processList = []
      this.getIpconfigFromApi('innerIp').then(ip => {
        this.ipServer = ip
        this.options = {
          target: 'http://' + ip + '/webapi/rfile/chunkUpload',
          chunkSize: 10 * 1024 * 1024,
          testChunks: false, // 是否测试分片
        }
      })
      let tab = {
        name: this.activeName
      }
      this.tabsHandleClick(tab)
      let that = this
      clearInterval(this.timer)
      this.timer = setInterval(function () {
        if (that.$refs.uploader.fileList.length > 0) {
          let completed = true
          for (let fileItem of that.$refs.uploader.fileList) {
            if (fileItem.completed) {
              if (fileItem.isFolder && !fileItem.isPut) {
                that.putFileRecordHandle(fileItem,that.selectItem.id)
              }
            } else {
              completed = false
            }
          }
          console.log(completed)
          if (completed) {
            that.$refs.uploader.uploader.cancel()
          }
        }
      }, 10 * 1000)
    },
    tabsHandleClick (tab, event) {
      if (tab.name === 'first') {
        // 触发‘上传成果’事件
        this.getInfoByProjectNo(this.projectNo).then( info => {
          this.projectInfo = info
          this.getRfileList(info.contractName)
        })
      } else {
        // 触发‘归档文件’事件
        this.getInfoByProjectNo(this.projectNo).then( info => {
          this.projectInfo = info
          this.getRfileList(info.contractName)
          this.params = {
            ipServer: this.ipServer,
            projectNo: this.projectNo,
            contractName: info.contractName,
            options: {
              target: 'http://' + this.ipServer + '/final/file/chunkUpload',
              chunkSize: 10 * 1024 * 1024,
              testChunks: false, // 是否测试分片
            }
          }
          setTimeout(() => {this.$refs.finalFile.init() },1500)
        })
      }
    },
    // 保存上传文件记录
    putFileRecordHandle (fileItem,parentId) {
      this.$http({
        url: 'http://' + this.ipServer + '/webapi/rfile/save',
        method: 'post',
        data: this.$http.adornData({
          'fileName': fileItem.name,
          'parentId': parentId,
          'dir': fileItem.isFolder,
          'operation': '保存文件',
          'createUsername': this.username,
          'modifyUsername': this.username,
        })
      }).then(({data}) => {
        if (data && data.code === 0) {
          this.getRfileList(this.contractItem.fileName)
          this.getRListByPid(this.selectItem.id)
          fileItem.isPut = true
        } else {
          this.$message.error(data.msg)
        }
      })
    },
    // 获取文件大小
    getFileSizeHandle(size) {
      return getFileSize(size)
    },
    // 根据数组获取文件路径
    getDirByPatharr () {
      let cPath = ''
      this.curpath.forEach((item,index) => {
        cPath += item + '/'
      })
      return cPath
    },
    // 获取文件路径
    getFilepath (num) {
      this.curpath = this.curpath.slice(0,num + 1)
      return this.getDirByPatharr()
    },
    // 跳转路径
    changePath (path) {
      this.getFinalList(path)
    },
    // 获取项目基本信息
    getInfoByProjectNo (projectNo) {
      return new Promise((resolve, reject) => {
        this.$http({
          url: this.$http.adornUrl(`/project/projectInfo/info/${projectNo}`),
          method: 'get',
          params: this.$http.adornParams()
        }).then(({data}) => {
          if (data && data.code === 0) {
            resolve(data.projectInfo)
          } else {
            this.$message.error(data.msg)
            reject(data.msg)
          }
        })
      })
    },
    // 获取参数Ip
    getIpconfigFromApi (keyParm) {
      this.loading = true
      return new Promise((resolve, reject) => {
        this.$http({
          url: this.$http.adornUrl('/sys/config/getNameByKey'),
          method: 'get',
          params: this.$http.adornParams({
            key: keyParm
          })
        }).then(({data}) => {
          if (data && data.code === 0) {
            resolve(data.config.paramValue)
          } else {
            this.$message.error(data.msg)
            reject(data)
          }
        })
      })
    },
    getRfileList (fileName) {
      this.$http({
        url: 'http://' + this.ipServer + '/webapi/rfile/innerList',
        method: 'get',
        params: this.$http.adornParams({
          parentId: 0,
          fileName: fileName,
          userName: this.username,
          dir: true
        })
      }).then(({data}) => {
        this.loading = false
        if (data && data.code === 0) {
          this.projectFiletList = data.innerList
          this.contractItem = data.entity
        } else {
          this.$message.error(data.msg)
        }
      }).catch(error => {
        this.isConnected = false
        this.loading = false
      })
    },
    // 根据父类Id 获取列表
    getRListByPid (pid) {
      this.$http({
        url: 'http://' + this.ipServer + '/webapi/rfile/getRListByPid',
        method: 'get',
        params: this.$http.adornParams({
          parentId: pid
        })
      }).then(({data}) => {
        if (data && data.code === 0) {
          this.dataList = data.list
        } else {
          this.$message.error(data.msg)
        }
      })
    },
    // 添加记录文件
    addProFileHandle () {
      let pItem = {
        fileName: '',
        isFouce: true,
        dir: true,
        createUsername: this.username,
        parentId: 0
      }
      this.projectFiletList.push(pItem)
    },
    // 删除项目文件
    deletePfileHandle (item) {
      this.$confirm('是否删除项目文件【' + item.fileName + '】', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        this.$http({
          url: 'http://' + this.ipServer + '/webapi/rfile/deleteRfile',
          method: 'post',
          data: this.$http.adornData({
            id: item.id,
            fileName: item.fileName,
            dir: item.dir
          })
        }).then(({data}) => {
          this.loading = false
          if (data && data.code === 0) {
            this.getRfileList(this.contractItem.fileName)
            this.getRListByPid(this.selectItem.id)
          } else {
            this.$message.error(data.msg)
          }
        })
      })
    },
    // 编辑档案 （修改名称）
    editArchHandle (item) {
      for (let fileItem of this.projectFiletList) {
        if (item.fileName === fileItem.fileName) {
          item.isFouce = true
          item.oldName = item.fileName
        }
      }
      this.bTabKey = Math.random()
    },
    // 下载文件
    downloadFileHandle (fileItem) {
      window.location.href = 'http://' + this.ipServer + '/' + this.projectNo + fileItem.fileName
    },
    // 打开项目文件
    openProFileHandle (item) {
      this.selectItem = item
      this.getRListByPid(item.id)
    },
    querySearchAsync (queryString, cb) {
      var list = [{}]
      if (!stringIsNull(queryString.trim())) {
        // 从后台获取到对象数组
        this.$http({
          url: 'http://' + this.ipServer + '/final/file/list',
          method: 'get',
          params: this.$http.adornParams({
            key: queryString.trim()
          })
        }).then(({data}) => {
          list = data.list.map( (item,index) => {
            return {
              id: index,
              value: item
            }
          })
          // 如果列表不存在 则提示是否创建
          if (stringIsNull(data.list.find(item => item === queryString.trim()))) {
            this.isCreated = true
          } else {
            this.isCreated = false
          }
          cb(list)
        })
      }
    },
    // 文本框输入失去焦点 （编辑上传目录文件）
    blurArchHandle (item) {
      item.isFouce = false
      this.aTabKey = Math.random()
      if (stringIsNull(item.fileName.trim()) || (item.oldName === item.fileName.trim()) ) {
        this.init()
      } else {
        this.$http({
          url: 'http://' + this.ipServer + '/webapi/rfile/update',
          method: 'post',
          data: this.$http.adornData({
            id: item.id,
            filePath: this.projectInfo.contractName,
            username: this.username,
            parentId: this.contractItem.id,
            newName: item.fileName.trim(),
            oldName: item.oldName
          })
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.selectItem = null
            this.init()
            this.loading = false
          } else {
            this.$message.error(data.msg)
          }
        })
      }
    },
    // 归档文件
    saveFinalFileHandle () {
      var itemList = this.dataListSelections.map(item => {
        return item
      })
      this.$confirm('确定归档操作', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$refs.finalFile.sendCopyMessage(itemList)
        // console.log(ids)
      })
    },
    // 上传文件成功
    onFileSuccess (rootFile, file, response, chunk) {
      this.getRfileList(this.contractItem.fileName)
      this.getRListByPid(this.selectItem.id)
    },
    onFileAdd (file) {
      let rPath = file.file.relativePath.substring(0,file.file.relativePath.lastIndexOf(file.file.name))
      // file.relativePath = this.projectNo + '/' + rPath
      console.log(this.selectItem)
      file.relativePath = this.selectItem.id + ',' + this.username + ',' + rPath
      file.createUsername = this.username
      this.panelShow = true
    },
    // 上传时移除文件
    onFileRemove (file) {
      // console.log(file)
      let that = this
      // 延时两秒 删除上传未完成的 暂时文件
      if (file.completed === false) {
        setTimeout(function () {
          let confItem = {
            fileName: file.name + '.conf',
            dir: false
          }
          that.deleteFileFromApi(confItem)
          let tempItem = {
            fileName: file.uniqueIdentifier + '_tmp',
            dir: false
          }
          that.deleteFileFromApi(tempItem)
        },2000)
      }
    },
    // 多选
    selectionChangeHandle (val) {
      this.dataListSelections = val
    },
  }
}
</script>

<style lang="scss" scoped>
@import "src/assets/scss/_variables.scss";
  .select_option /deep/ {
    .el-input__inner {
      color: red;
    }
  }
  .ach_title{
    padding: 0;
    justify-content: space-between;
    display: flex
  }
  .span_title {
    font-size: 19px;
    font-weight: 700;
  }
  .section {
    //box-shadow: inset 6px 1px 13px -2px $--color-primary;
    min-height: 200px;
    width: 100%;
    .section_404 {
      text-align: center;
    }
  }
  .file_section {
    padding: 6px;
    display: inline-block;
    width: 100%;
    .file_item {
      width: 165px;
      text-align: center;
      margin-left: 5px;
      padding: 3px;
      text-align: left;
      display: flex;
      position: relative;
      -webkit-user-select:none ;
      -moz-user-select:none;
      .file_item_span{
        width: 125px;
        .file_item_span_nom {
          font-weight: bolder;
          overflow: hidden;
          white-space:nowrap;
          word-wrap:break-word;
          text-overflow:ellipsis;//文字隐藏后添加省略号
        }
      }
      i {
        font-size: 45pt;
        margin-top: 2px;
      }
      &:hover {
        cursor: pointer;
        background: $--color-primary;
        .btn_card {
          display: block;
          background-color: #0c0c0c9f;
          position: absolute;
          height: 100%;
          width: 100%;
        }
        span {
          white-space:normal;
          overflow:auto;
          color: white;
        }
      }
    }
    .btn_card {
      background-color: #0c0c0c9f;
      position: absolute;
      height: 100%;
      width: 100%;
      display: none;
      z-index: 3;
      .btn_line {
        padding: 10px;
        vertical-align: middle;
        position: absolute;
        top:15%;
        width: 100%;
      }
    }
  }

.popup-container {
  position: relative;
  box-shadow: -2px -4px 5px $navbar--background-color;
  border: 1px $navbar--background-color solid;
  //right: 20px;
  //bottom: 30px;
  padding: 1px;
  z-index: 2001;
  width: 100%;
  -moz-user-select:none;		/* 火狐 */
  -webkit-user-select:none;	/* 谷歌 */
  -ms-user-select:none;		/* IE */
  user-select:none;
  .header {
    padding: 6px;
    background: $--color-primary;
    color: whitesmoke;
    display: flex;
    justify-content: space-between;
    width: 100%;
    .title_span {
      font-size: 15pt;
      font-weight: 700;
    }
    .title_btn{
      padding-right: 5px;
      i {
        font-size: 19pt;
        font-weight: 700;
        cursor: pointer;
      }
      i:hover{
        color: red;
      }
    }
  }
  .content {
    background: beige;
    height: 200px;
    overflow-y: auto;
  }
}
</style>
